package com.wenli.viewpagerdemo;

import android.app.Activity;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends Activity implements OnPageChangeListener {

    private List<ImageView> imageViewList; // Viewpager的数据
    private ViewPager mViewPager;
    private LinearLayout llPointGroup;
    private TextView tvImageDescription;
    private String[] imageDescriptions;
    private int previousPosition = 0; // 前一个被选中的position

    private boolean isStop = false;

    @Override
    protected void onDestroy() {
        super.onDestroy();

        // 把正在循环切换的任务给停止掉
        isStop = true;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initView();

        new Thread(new Runnable() {
            @Override
            public void run() {
                // 每隔5秒钟, 来切换一张图片
                while (!isStop) {
                    System.out.println("正在切换图片..");

                    // 运行在主线程中的任务
                    runOnUiThread(new Runnable() {
                        public void run() {
                            mViewPager.setCurrentItem(mViewPager.getCurrentItem() + 1);
                        }

                        ;
                    });
                    SystemClock.sleep(5000);
                }
            }
        }).start();
    }

    private void initView() {
        mViewPager = (ViewPager) findViewById(R.id.viewpager);
        tvImageDescription = (TextView) findViewById(R.id.tv_image_description);
        llPointGroup = (LinearLayout) findViewById(R.id.ll_point_group);

        initData();

        MyAdapter mAdapter = new MyAdapter();
        mViewPager.setAdapter(mAdapter); // 当执行完此行代码, ViewPager会去找MyAdapter去要数据.
        mViewPager.setOnPageChangeListener(this);

        // 设置默认选中的点和图片对应的描述信息.
        previousPosition = 0;
        llPointGroup.getChildAt(previousPosition).setEnabled(true);
        tvImageDescription.setText(imageDescriptions[previousPosition]);


        // 把ViewPager设置为默认选中Integer.MAX_VALUE / 2;

        int m = (Integer.MAX_VALUE / 2) % imageViewList.size();
        int currentPosition = Integer.MAX_VALUE / 2 - m;
        mViewPager.setCurrentItem(currentPosition);
    }

    private void initData() {
        imageDescriptions = new String[]{
                "巩俐不低俗，我就不能低俗",
                "扑树又回来啦！再唱经典老歌引万人大合唱",
                "揭秘北京电影如何升级",
                "乐视网TV版大派送",
                "热血屌丝的反杀"
        };

        int[] imageResIDs = {
                R.drawable.a,
                R.drawable.b,
                R.drawable.c,
                R.drawable.d,
                R.drawable.e
        };

        imageViewList = new ArrayList<ImageView>();

        ImageView iv;
        View v;
        LayoutParams params;
        for (int i = 0; i < imageResIDs.length; i++) {
            iv = new ImageView(this);
            iv.setBackgroundResource(imageResIDs[i]);
            imageViewList.add(iv);

            // 每循环一次需要向LinearLayout中添加一个点的view对象
            v = new View(this);
            v.setBackgroundResource(R.drawable.point_bg);
            params = new LayoutParams(5, 5);
            if (i != 0) {
                // 当前不是第一个点, 需要设置左边距
                params.leftMargin = 5;
            }
            v.setLayoutParams(params);
            v.setEnabled(false);
            llPointGroup.addView(v);
        }
    }

    class MyAdapter extends PagerAdapter {

        /**
         * 返回的int的值, 会作为ViewPager的总长度来使用.
         */
        @Override
        public int getCount() {
            return Integer.MAX_VALUE;
        }

        /**
         * 判断是否使用缓存, 如果返回的是true, 使用缓存. 不去调用instantiateItem方法创建一个新的对象
         */
        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        /**
         * 初始化一个条目
         * position 就是当前需要加载条目的索引
         */
        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            // 把position对应位置的ImageView添加到ViewPager中
            ImageView iv = imageViewList.get(position % imageViewList.size());
            mViewPager.addView(iv);
            // 把当前添加ImageView返回回去.
            return iv;
        }

        /**
         * 销毁一个条目
         * position 就是当前需要被销毁的条目的索引
         */
        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            // 把ImageView从ViewPager中移除掉
            mViewPager.removeView(imageViewList.get(position % imageViewList.size()));
        }
    }

    @Override
    public void onPageScrolled(int position, float positionOffset,
                               int positionOffsetPixels) {

    }

    /**
     * 当ViewPager页面被选中时, 触发此方法.
     *
     * @param position 当前被选中的页面的索引
     */
    @Override
    public void onPageSelected(int position) {

        int newPosition = position % imageViewList.size();

        // 把当前选中的点给切换了, 还有描述信息也切换
        llPointGroup.getChildAt(previousPosition).setEnabled(false);
        llPointGroup.getChildAt(newPosition).setEnabled(true);
        tvImageDescription.setText(imageDescriptions[newPosition]);

        // 把当前的索引赋值给前一个索引变量, 方便下一次再切换.
        previousPosition = newPosition;
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }
}
